package com.dmxtechnologies.community.war.handler;

import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerFactory;
import javax.faces.context.FacesContext;

import com.sun.faces.application.ApplicationAssociate;
import com.sun.faces.context.AjaxExceptionHandlerImpl;
import com.sun.faces.context.ExceptionHandlerImpl;

public class CMSExceptionHandlerFactory extends ExceptionHandlerFactory {

	private ApplicationAssociate associate;
	
	@Override
	public ExceptionHandler getExceptionHandler() {
		FacesContext fc = FacesContext.getCurrentInstance();
		if (fc.getPartialViewContext().isAjaxRequest()) {
			return new AjaxExceptionHandlerImpl(new ExceptionHandlerImpl(Boolean.TRUE));
		}
		ApplicationAssociate associate = getAssociate(fc);
		return new CMSExceptionHandler(
				((associate != null) ? associate.isErrorPagePresent() : Boolean.TRUE));
	}

	private ApplicationAssociate getAssociate(FacesContext ctx) {
		if (associate == null) {
			associate = ApplicationAssociate.getCurrentInstance();
			if (associate == null) {
				associate = ApplicationAssociate.getInstance(ctx.getExternalContext());
			}
		}
		return associate;
	}
}
